package com.xx.service.impl;

import com.xx.bean.User;
import com.xx.mapper.UserMapper;
import com.xx.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class UserServiceImpl implements UserService {
    public static SqlSession getSqlSession() throws IOException {
        String resource = "mybatis-config.xml";
        //读取类路径下的配置文件得到输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象，相当于Connection对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }


    @Override
    public void doRegister(User user) {
        try {
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            User exitUser = mapper.selectUserByName(user.getUsername());
            if (exitUser != null) {
                throw new RuntimeException("用户名注册失败");
            }
            mapper.addUser(user);
        } catch (Exception e) {
            throw new RuntimeException("异常");
        }
    }

    public User doLogin(User user) throws Exception {
//        1.根据用户名查询用户名称
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        User loginUser = mapper.selectUserByName(user.getUsername());
        if (loginUser != null) {
//                说明用户名正确
            if (loginUser.getUserPwd().equals(user.getUserPwd())) {
                //密码正确登录
                return loginUser;
            } else {
                //密码错误
                throw new RuntimeException("密码错误");
            }
        }
        throw new RuntimeException("用户名错误");
    }
}
